package com.aids_malaria.ui.datacollect;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import com.aids_malaria.R;
import com.aids_malaria.adapter.CountySelectAdapter;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.http.response.WorkAreaResponse;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.luck.picture.lib.rxbus2.RxBus;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class CountySelectActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_county_name)
    EditText et_county_name;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<AreaC> mData = new ArrayList<>();
    private List<AreaC> mOriginalData = new ArrayList<>();
    private CountySelectAdapter countySelectAdapter;

    private int type;
    private boolean isCurrentArea;//是否现住址，是则只能选择设置了的工作区域

    @Override
    protected int getLayoutId() {
        return R.layout.activity_county_select;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.county_select));
        initRefreshLayout();
        et_county_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String inputStr = charSequence.toString();
                mData.clear();
                for(int j=0; j<mOriginalData.size(); j++){
                    if(mOriginalData.get(j).getCounty_name().contains(inputStr)){
                        mData.add(mOriginalData.get(j));
                    }
                }
                countySelectAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        type = getIntent().getIntExtra(Events.TYPE_KEY,0);
        isCurrentArea = getIntent().getBooleanExtra("is_current",false);
        initRecycleView();
        getCounty();
    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
                getCounty();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                getCounty();
            }
        });
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        countySelectAdapter = new CountySelectAdapter(mContext,
                R.layout.item_county_select,mData);
        rv_data.setAdapter(countySelectAdapter);
        countySelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                AreaC areaC = mData.get(position);
                Events.CountySelectEvent countySelectEvent = new Events.CountySelectEvent();
                countySelectEvent.setAreaC(areaC);
                countySelectEvent.setType(type);
                RxBus.getDefault().post(countySelectEvent);
                setResult(201);
                finish();
            }
        });
    }

    /**
     * 获取行政县数据
     *
     */
    private void getCounty() {
        if(isOnLine()){
            String countyName = et_county_name.getText().toString().trim();
            RetrofitFactory.getInstance().createApi(RetrofitApi.class).getCounty("", countyName)
                    .compose(RxScheduler.rxSchedulerTransform())
                    .subscribe(new BaseObserver<List<AreaC>>() {

                        @Override
                        protected void onStart() {
                            getLoadingDialog().show();
                        }

                        @Override
                        protected void onSuccess(List<AreaC> data) throws Exception {
                            mData.clear();
                            mData.addAll(data);
                            mOriginalData.clear();
                            mOriginalData.addAll(data);
                            countySelectAdapter.notifyDataSetChanged();
                        }

                        @Override
                        protected void onFinish() {
                            getLoadingDialog().dismiss();
                        }
                    });
        }else{
//            ArrayList<AreaC> areaCList = LiteOrmUtil.getLiteOrm().query(AreaC.class);
            List<AreaC> areaCList = DBManager.get().areaCDao().getAll();
            if(isCurrentArea){
                List<WorkAreaResponse> workAreaResponseList = DBManager.get().workAreaResponseDao().getAll();
                if(workAreaResponseList.size() > 0){
                    WorkAreaResponse workAreaResponse = workAreaResponseList.get(0);
                    mData.clear();
                    mOriginalData.clear();
                    for (AreaC areaC : areaCList) {
                        //匹配工作区域的行政县
                        if(workAreaResponse.getCounty_code().equals(areaC.getCounty_code())){
                            mData.add(areaC);
                            mOriginalData.add(areaC);
                        }
                    }
                }
            }else{
                mData.clear();
                mData.addAll(areaCList);
                mOriginalData.clear();
                mOriginalData.addAll(areaCList);
            }
            countySelectAdapter.notifyDataSetChanged();
        }

    }

}
